package org.queryexecutor.swing.frames.components.methods;

import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JComboBox;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTable;

import org.queryexecutor.database.DatabaseConnection;
import org.queryexecutor.database.drivers.DatabaseDrivers;
import org.queryexecutor.main.Main;
import org.queryexecutor.swing.dialogs.DatabaseLogin;
import org.queryexecutor.swing.frames.MainFrame;
import org.queryexecutor.swing.panels.LocalFilePanel;
import org.queryexecutor.swing.panels.ServerPanel;

public class ButtonMethods
{
	
	private DatabaseLogin dbLogin = DatabaseLogin.getInstance(MainFrame.getInstance());
	private static ButtonMethods bMethods;
	
	private ButtonMethods(){}
	
	public static ButtonMethods getInstance()
	{
		if(bMethods == null){
			bMethods = new ButtonMethods();
		}
		return bMethods;
	}
	
	public void btnCancelOnActionPerformed(ActionEvent e)
	{
		System.exit(0);
	}
	
	public void btnLogInOnActionPerformed(ActionEvent e, JPanel panel)
	{
		ServerPanel sPanel;
		LocalFilePanel lPanel;
		JComboBox cb = this.dbLogin.getDbTypesCB();
		if(panel instanceof ServerPanel) {
			sPanel = (ServerPanel) panel;
			try {
				serverPanel(sPanel, (DatabaseDrivers) cb.getSelectedItem());
			} catch(SQLException e1) {
				Main.showException(e1, this.dbLogin);
			}
		} else {
			lPanel = (LocalFilePanel) panel;
		}
	}
	
	private void serverPanel(ServerPanel panel, DatabaseDrivers driver) throws SQLException
	{
		String server = panel.getTxtServer().getText();
		if(!isNull(server, "Server Name"))
			return;

		String database = panel.getTxtDatabase().getText();
		if(!isNull(database, "Database Name"))
			return;
		
		String username = panel.getTxtUsername().getText();
		if(!isNull(username, "Username"))
			return;
		
		String password = String.valueOf(panel.getTxtPassword().getPassword());
		if(!isNull(password, "Password"))
			return;
		
		DatabaseConnection con = DatabaseConnection.getInstance();
		boolean connected = con.connect(driver.getConnectionString()
				.replace("[database]", database).replace("[server]", server), username, password);
		if(connected) {
			this.dbLogin.dispose();
		}
	}
	
	private boolean isNull(String value, String parameter)
	{
		if(value == null || value.equals("")){
			Main.showMessage(this.dbLogin, parameter + " is required!", true);
			return false;
		}else{
			return true;
		}
	}
	
	public void mntmExecuteAllOnActionPerformed(ActionEvent e, String query, JTable table)
	{
		MainFrame.getInstance().getQueryTableModel().initDB();
		MainFrame.getInstance().getQueryTableModel().setQuery(query);
	}
	
	
}
